package com.gaogzhen.datastructure.linear.linkedList;

import java.util.*;

public class SequenceList<T> implements Iterable<T> {

    private static final int DEFAULT_CAPACITY = 10;
    private static final Object[] EMPTY_ELEMENTDATA = {};
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    transient Object[] elementData;
    private int size;

    protected transient int modCount = 0;

    public SequenceList(int initCapacity) {
        if (initCapacity > 0) {
            this.elementData = new Object[initCapacity];
        } else if (initCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: " +
                    initCapacity);
        }
    }

    /**
     * 清空表
     */
    public void clear() {
        modCount++;

        for (int i = 0; i < size; i++) {
            this.elementData[i] = null;
        }

        size = 0;
    }

    T elementData(int index) {
        return (T) elementData[index];
    }

    /**
     * 获取表中第i个元素
     *
     * @param i 索引
     * @return 索引i处的值
     */
    public T get(int i) {
        rangeCheck(i);

        return elementData(i);
    }

    /**
     * 用指定值替换指定位置的元素
     *
     * @param index   指定位置
     * @param element 指定值
     * @return 指定位置原先的值
     */
    public T set(int index, T element) {
        rangeCheck(index);

        T oldValue = elementData(index);
        this.elementData[index] = element;
        return oldValue;
    }

    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private String outOfBoundsMsg(int index) {
        return "Index: " + index + ", Size: " + size;
    }

    /**
     * 获取元素t在表中索引
     * 如果元素不在表中，返回-1
     *
     * @param o 目标元素
     * @return 元素t在表中索引
     */
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++) {
                if (this.elementData[i] == null)
                    return i;
            }
        } else {
            for (int i = 0; i < size; i++) {
                if (o.equals(this.elementData[i]))
                    return i;
            }
        }
        return -1;
    }

    /**
     * 把元素t插入表中
     * 默认插入末尾
     *
     * @param t 新增元素t
     */
    public boolean insert(T t) {
        ensureCapacityInternal(size + 1);
        this.elementData[size++] = t;
        return true;
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }

    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 在索引i处插入元素t
     *
     * @param t     新增元素t
     * @param index 插入位置
     */
    public void insert(int index, T t) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = t;
        size++;
    }

    /**
     * 判断表是否为空
     *
     * @return 表为空, true;表不为空,false
     */
    public boolean isEmpty() {
        return this.size == 0;
    }

    /**
     * 表的长度
     *
     * @return 表的长度
     */
    public int size() {
        return size;
    }

    /**
     * 删除索引i处的元素
     *
     * @param index 要被删除的元素位置
     * @return 被删除的元素
     */
    public T remove(int index) {
        rangeCheck(index);

        modCount++;
        T oldValue = elementData(index);
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                    numMoved);
        elementData[--size] = null;
        return oldValue;
    }

    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
                    ? EMPTY_ELEMENTDATA
                    : Arrays.copyOf(elementData, size);
        }
    }

    @Override
    public Iterator<T> iterator() {
        return new SIterator<>();
    }

    private class SIterator<T> implements Iterator<T> {

        private int cursor;
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        @Override
        public boolean hasNext() {
            return cursor != size;
        }

        @Override
        public T next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = SequenceList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (T) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                SequenceList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        s.append("(");
        for (int i = 0; i < this.size; i++) {
            if (i == size - 1) {
                s.append(this.elementData[i]);
            } else {
                s.append(this.elementData[i]).append(",");
            }
        }
        s.append(")");
        return s.toString();
    }
}
